#include "qconfigfile_base.h"
#include <QDebug>
#include <QDir>
#include <QVariant>
#include "file_base.h"
//-----------------------------------------------------------------------------

QConfigFile::QConfigFile(QString subdir_name, QString module_name):
    QDomDocument()
{
    IsReady = false;
    ModuleName = module_name;

    FullDirName  = QFileBase::ConcatDirFile(QDir::homePath(), subdir_name);
    FullFileName = QFileBase::ConcatDirFile(FullDirName,      module_name+".cfg");

    if(CheckDir(FullDirName) && CheckFile(FullFileName)){
        IsReady = true;
    }
}
//-----------------------------------------------------------------------------
QConfigFile::~QConfigFile()
{
    WriteFile();
}

//-----------------------------------------------------------------------------
bool QConfigFile::CheckDir(QString full_dir_name)
{
    QDir      dir(full_dir_name);
    QFileInfo di (full_dir_name);

    if(di.exists()){
        if(!di.isDir()){
            qDebug() << QObject::trUtf8("QConfigFile::CheckDirExists() Ошибка!!!") << full_dir_name << QObject::trUtf8(" не является каталогом!");
            return false;
        }
    }else{
        if(!dir.mkpath(full_dir_name)){
            qDebug() << QObject::trUtf8("QConfigFile::CheckDirExists() Ошибка!!! Невозможно создать каталог:") << full_dir_name;
            return false;
        }
    }
    return true;
}
//-----------------------------------------------------------------------------
bool QConfigFile::CheckFile(QString full_file_name)
{
    QFileInfo fi(full_file_name);
    if(fi.exists()){
        if(fi.isFile()) return true;
        else{
            qDebug() << QObject::trUtf8("QConfigFile::CheckFileExists() Ошибка!!!") << full_file_name << QObject::trUtf8(" не является файлом!");
            return false;
        }
    }else{
        return CreateNewFile(full_file_name);
    }
}
//-----------------------------------------------------------------------------
bool QConfigFile::CreateNewFile(QString full_file_name) // Создаем файл с 0, если его еще нет
{
    QFile file_in(full_file_name);
    if(!file_in.open(QFile::WriteOnly | QFile::Text)){
        qDebug() << QObject::trUtf8("QConfigFile::CreateNewFile() Ошибка при создании файла конфигурации! ") << full_file_name;
        return false;
    }
    QTextStream out(&file_in);
    out.setCodec("UTF-8");
    out << " ";

    file_in.close();
    return true;
}
//-----------------------------------------------------------------------------
bool QConfigFile::ReadFile()
{
    if(!IsReady){
        qDebug() << QObject::trUtf8("QConfigFile::ReadFile() ERROR!!! isReady==false");
        return false;
    }

    QFile file_in(FullFileName);
    if(!file_in.open(QFile::ReadOnly)){
        qDebug() << "QConfigFile::ReadFile() ERROR!!! open(" << FullFileName << ")==false";
        return false;
    }

    QString errorMsg;
    int errorLine, errorColumn;
    if(!setContent(&file_in, false, &errorMsg, &errorLine, &errorColumn)){
        file_in.close();
        qDebug() << "QConfigFile::ReadFile() ERROR!!! setContent(" << FullFileName << ")==false";
        qDebug() << "QConfigFile::ReadFile() ERROR!!! errorMsg=" << errorMsg <<  " errorLine=" <<  errorLine << " errorColumn=" << errorColumn;
        return false;
    }
    file_in.close();
    return true;
}

//-----------------------------------------------------------------------------
bool QConfigFile::WriteFile()
{
    if(!IsReady){
        qDebug() << QObject::trUtf8("QConfigFile::WriteFile() ERROR!!! isReady==false");
        return false;
    }


    QFile file_out(FullFileName);
    if(!file_out.open(QFile::WriteOnly)){
        qDebug() << "QConfigFile::WriteFile() ERROR!!! open(" << FullFileName << ")==false";
        return false;
    }

    QTextStream out(&file_out);
    out.setCodec("UTF-8");

    save(out, 4, QDomNode::EncodingFromTextStream);
    file_out.close();
    return true;
}

//-----------------------------------------------------------------------------
QDomElement QConfigFile::GetRoot(const QString& root_name)
{
    QDomNodeList nlist = elementsByTagName (root_name) ;
    QDomElement root_elem;
    if(nlist.isEmpty()){
        root_elem = createElement(root_name);
        appendChild (root_elem);
    }else{
        root_elem = nlist.at(0).toElement();
        for(int i=1; i<nlist.count(); i++)
            nlist.at(i).clear();
    }
    return root_elem;
}

//-----------------------------------------------------------------------------
QString  QConfigFile::getAttribS(QDomElement root_el,
                                const QString& elem_name, const QString& attr_name,
                                const QString& def_val)
{
    QString attr_val("");
    QDomNodeList nlist = root_el.elementsByTagName(elem_name);
    if(nlist.isEmpty()){
        attr_val = setAttribS(root_el, elem_name, attr_name, def_val);
    }else{
        attr_val  = nlist.at(0).toElement().attribute(attr_name);
        if(attr_val.length()<=0){
            attr_val = setAttribS(root_el, elem_name, attr_name, def_val);
        }
    }
    return attr_val;
}

//-----------------------------------------------------------------------------
QString QConfigFile::setAttribS(QDomElement root_el, const QString& elem_name, const QString& attr_name, QString attr_val)
{
    QDomNodeList nlist = root_el.elementsByTagName(elem_name);
    if(nlist.isEmpty()){
        QDomElement elem_1 = createElement(elem_name);
        elem_1.setAttribute(attr_name, attr_val);
        root_el.appendChild(elem_1);
    }else{
        nlist.at(0).toElement().setAttribute(attr_name,   attr_val);
        for(int i=0; i<nlist.count(); i++)
            nlist.at(i).clear();
    }
    return attr_val;
}
//-----------------------------------------------------------------------------
bool QConfigFile::SetParam(const QString& param_name, QVariant  param_val)
{
    if(!IsReady) return false;
    setAttribS(GetRoot(ModuleName), param_name, "val", param_val.toString());
    return true;
}
//-----------------------------------------------------------------------------
bool QConfigFile::GetParam(const QString& param_name, QVariant &param_val)
{
    if(!IsReady) return false;
    param_val = getAttribS(GetRoot(ModuleName), param_name, "val", "0");
    return true;
}


